package de.velvettear.squirrel.gui;

import java.util.Vector;

import org.jivesoftware.smack.SmackAndroid;

import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import de.velvettear.squirrel.R;
import de.velvettear.squirrel.adapter.ContactListAdapter;
import de.velvettear.squirrel.kernel.Contact;
import de.velvettear.squirrel.kernel.Settings;
import de.velvettear.squirrel.kernel.Statics;
import de.velvettear.squirrel.util.AnimationHelper;
import de.velvettear.squirrel.util.ChatHelper;

public class ChatFrame extends FragmentActivity implements ActionBar.TabListener {
			
	private static Context context;
	private static Activity activity;
	
	private static ViewPager viewPager;
	private static SectionsPagerAdapter sectionsPagerAdapter;	
				
	private static ActionBar actionBar;
	
	// ContactListFragment
	private static LinearLayout ll_data;
	private static RelativeLayout rl_info;
	private static EditText et_status;
	private static Spinner sp_mode;
	private static ListView lv_contacts;
	private static ContactListAdapter adapter;
	
	// ChatFragment
	private static EditText et_message;
	private static ListView lv_chat;
	private static TextView tv_user;
	private static ImageView iv_icon;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_networkframe);

		actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		
		context = ChatFrame.this;
		activity= ChatFrame.this;
						
		sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

		viewPager = (ViewPager) findViewById(R.id.pager);
		viewPager.setAdapter(sectionsPagerAdapter);

		viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				actionBar.setSelectedNavigationItem(position);
			}
		});

		for (int i = 0; i < sectionsPagerAdapter.getCount(); i++) {
			actionBar.addTab(actionBar.newTab().setText(sectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
			actionBar.newTab();
		}										
	}
	
	public void onDestroy() {		
		ChatHelper.disconnect();
		
		super.onDestroy();
	}
			
	@Override
	public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		invalidateOptionsMenu();
		viewPager.setCurrentItem(tab.getPosition());		
	}

	@Override
	public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		
	}

	@Override
	public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		
	}
		
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);						
	}
			
	private static int getCurrentFragment() {
		return (int) sectionsPagerAdapter.getItemId(viewPager.getCurrentItem());
	}
		
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			switch (position) {
			
			case 0: return ContactListFragment.newInstance();
			
			case 1: return ChatFragment.newInstance();
						
			default: return ContactListFragment.newInstance();
			
			}
		}

		@Override
		public int getCount() {	
			return 2;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			switch (position) {
			case 0:
				return Statics.CONTACTLIST;
			case 1:
				return Statics.CHAT;
			}
			return null;
		}
	}
	
	public static class ContactListFragment extends Fragment implements OnItemClickListener, OnItemSelectedListener, TextWatcher {
			
		private static ArrayAdapter<String> spinnerAdapter;
		
		public ContactListFragment() {
			
		}

		public static ContactListFragment newInstance() {
			ContactListFragment fragment = new ContactListFragment();
			return fragment;
		}
		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_contactlist, container, false);
							
			ll_data = (LinearLayout) rootView.findViewById(R.id.contactlist_ll_data);
			rl_info = (RelativeLayout) rootView.findViewById(R.id.contactlist_rl_info);
			et_status = (EditText) rootView.findViewById(R.id.contactlist_et_status);			
			sp_mode = (Spinner) rootView.findViewById(R.id.contactlist_sp_mode);
			lv_contacts = (ListView) rootView.findViewById(R.id.contactlist_lv_contacts);						
						
			AnimationHelper.startAnimation(rl_info);
			
			et_status.setText(new Settings().getValueByName(Statics.SETTINGS_CHAT_STATUS));
			et_status.clearFocus();
			et_status.addTextChangedListener(this);
			
			spinnerAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, new String[] {Statics.CHAT_MODE_ONLINE, Statics.CHAT_MODE_BUSY, Statics.CHAT_MODE_AWAY, Statics.CHAT_MODE_DND});
			sp_mode.setAdapter(spinnerAdapter);
			
			sp_mode.setSelection(spinnerAdapter.getPosition(new Settings().getValueByName(Statics.SETTINGS_CHAT_MODE)));
			sp_mode.setOnItemSelectedListener(this);
			
			lv_contacts.setOnItemClickListener(this);
			
			ChatHelper.connect(guiHandler);
			
			return rootView;
		}
				
		public static void populateContactList(Vector<Contact> contactList) {
			adapter = new ContactListAdapter(context, R.layout.listview_contactlist, R.id.listview_contactlist_name, contactList);			
			OnItemClickListener tmpListener = lv_contacts.getOnItemClickListener();			
			lv_contacts.setAdapter(adapter);
			lv_contacts.setOnItemClickListener(tmpListener);
			
			AnimationHelper.stopAnimation(rl_info, true);			
			ll_data.setVisibility(View.VISIBLE);
		}
		
		@Override
		public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {			
			
			viewPager.setCurrentItem(getCurrentFragment() + 1);			
		}

		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
			Settings settings = new Settings();
			settings.getSettingsByName(Statics.SETTINGS_CHAT_MODE);
			if (settings.isValid()) {
				String currentMode = settings.m_sValue;
				String newMode = sp_mode.getSelectedItem().toString();
				if (!currentMode.equals(newMode)) {
					settings.m_sValue = newMode;
					settings.store();
					
					ChatHelper.setPresence(settings.m_sValue, et_status.getText().toString());
				}
			}
			settings = new Settings();
			settings.getSettingsByName(Statics.SETTINGS_CHAT_STATUS);
			if (settings.isValid()) {
				String currentStatus = settings.m_sValue;
				String newStatus = et_status.getText().toString();
				if (!currentStatus.equals(newStatus)) {
					settings.m_sValue = newStatus;
					settings.store();
				
					ChatHelper.setPresence(sp_mode.getSelectedItem().toString(), settings.m_sValue);
				}
			}
			
			et_status.setBackgroundColor(getResources().getColor(R.color.gray));
		}

		@Override
		public void onNothingSelected(AdapterView<?> parent) {
			
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			
		}

		@Override
		public void afterTextChanged(Editable s) {
			et_status.setBackgroundColor(Color.RED);
		}	
	}	
		
	public static class ChatFragment extends Fragment {
		
		public ChatFragment() {
		
		}

		public static ChatFragment newInstance() {
			ChatFragment fragment = new ChatFragment();
			return fragment;
		}
		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_chat, container, false);
					
			et_message = (EditText) rootView.findViewById(R.id.chat_et_message);
			lv_chat = (ListView) rootView.findViewById(R.id.chat_lv_list);
			tv_user = (TextView) rootView.findViewById(R.id.chat_tv_user);
			iv_icon = (ImageView) rootView.findViewById(R.id.chat_iv_user);
									
			return rootView;
		}
		
	}	
			
	public static Handler guiHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Bundle data = msg.getData();
			
			if (data.containsKey(Statics.COMMAND_DIALOG_CANCEL)) {
				activity.finish();
			} else if (data.containsKey(Statics.COMMAND_DIALOG_OK)) {
				if (data.containsKey(Statics.COMMAND_DIALOG_SPECIFIC)) {
					String command = data.getString(Statics.COMMAND_DIALOG_SPECIFIC);						
					if (command.equals(Statics.COMMAND_SETTINGS_CHAT)) {
						Intent settingsIntent = new Intent(context, SettingsFrame.class);
						settingsIntent.putExtra(Statics.COMMAND, Statics.COMMAND_SETTINGS_CHAT);
						context.startActivity(settingsIntent);
						activity.finish();
					} else if (command.equals(Statics.COMMAND_INTENT_SETTINGS)) {
						Intent settingsIntent = new Intent(android.provider.Settings.ACTION_SETTINGS);
						settingsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						context.startActivity(settingsIntent);
						activity.finish();
					} else if (command.equals(Statics.COMMAND_CHAT_ACCOUNTCREATION)) {
//						ChatHelper.registerAccount();
					}					
				}
			} else if (data.containsKey(Statics.COMMAND_CHAT_LOGIN)) {
				String status = data.getString(Statics.COMMAND_CHAT_LOGIN);
				if (status.equals(Statics.CHAT_LOGIN_OK)) {
					ChatHelper.getContactList(guiHandler);
				} else if (status.equals(Statics.CHAT_LOGIN_FAILED)) {
					ChatHelper.checkSettings(context, guiHandler);
				}
			} else if (data.containsKey(Statics.COMMAND_CHAT_CONTACTLIST)) {
				int count = Integer.parseInt(data.getString(Statics.COMMAND_CHAT_CONTACTLIST));
				Vector<Contact> contactList = new Vector<Contact>();
				for (int counter = 0; counter < count; counter++) {
					Contact contact = (Contact) data.getSerializable(String.valueOf(counter));
					contactList.add(contact);
				}
				
				ContactListFragment.populateContactList(contactList);
				ChatHelper.setPresence(sp_mode.getSelectedItem().toString(), et_status.getText().toString());
			} else if (data.containsKey(Statics.COMMAND_CHAT_PRESENCE)) {
				if (adapter != null) {
					String name = data.getString("name");
					String type = data.getString("type");
					String mode = data.getString("mode");
					String status = data.getString("status");
					
					adapter.updateContact(name, type, mode, status);					
				}
			}
		}
	};
	
}
